home *** CD-ROM | disk | FTP | other *** search
/ Aminet 31 / Aminet 31 (1999)(Schatztruhe)[!][Jun 1999].iso / Aminet / dev / cross / z88dk_v1.0s.lha / src / cpp / cpp4.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-08-12  |  16.8 KB  |  619 lines

  1. /*
  2.  *                C P P 4 . C
  3.  *        M a c r o  D e f i n i t i o n s
  4.  *
  5.  * Edit History
  6.  * 31-Aug-84    MM    USENET net.sources release
  7.  * 04-Oct-84    MM    __LINE__ and __FILE__ must call ungetstring()
  8.  *            so they work correctly with token concatenation.
  9.  *            Added string formal recognition.
  10.  * 25-Oct-84    MM    "Short-circuit" evaluate #if's so that we
  11.  *            don't print unnecessary error messages for
  12.  *            #if !defined(FOO) && FOO != 0 && 10 / FOO ...
  13.  * 31-Oct-84    ado/MM    Added token concatenation
  14.  *  6-Nov-84    MM    Split off eval stuff
  15.  */
  16.  
  17. #include    <stdio.h>
  18. #include    <ctype.h>
  19. #include    "cppdef.h"
  20. #include    "cpp.h"
  21. /*
  22.  * parm[], parmp, and parlist[] are used to store #define() argument
  23.  * lists.  nargs contains the actual number of parameters stored.
  24.  */
  25. static char    parm[NPARMWORK + 1];    /* define param work buffer     */
  26. static char    *parmp;            /* Free space in parm        */
  27. static char    *parlist[LASTPARM];    /* -> start of each parameter    */
  28. static int    nargs;            /* Parameters for this macro    */
  29.  
  30. dodefine()
  31. /*
  32.  * Called from control when a #define is scanned.  This module
  33.  * parses formal parameters and the replacement string.  When
  34.  * the formal parameter name is encountered in the replacement
  35.  * string, it is replaced by a character in the range 128 to
  36.  * 128+NPARAM (this allows up to 32 parameters within the
  37.  * Dec Multinational range).  If cpp is ported to an EBCDIC
  38.  * machine, you will have to make other arrangements.
  39.  *
  40.  * There is some special case code to distinguish
  41.  *    #define foo    bar
  42.  * from    #define foo()    bar
  43.  *
  44.  * Also, we make sure that
  45.  *    #define    foo    foo
  46.  * expands to "foo" but doesn't put cpp into an infinite loop.
  47.  *
  48.  * A warning message is printed if you redefine a symbol to a
  49.  * different text.  I.e,
  50.  *    #define    foo    123
  51.  *    #define foo    123
  52.  * is ok, but
  53.  *    #define foo    123
  54.  *    #define    foo    +123
  55.  * is not.
  56.  *
  57.  * The following subroutines are called from define():
  58.  * checkparm    called when a token is scanned.  It checks through the
  59.  *        array of formal parameters.  If a match is found, the
  60.  *        token is replaced by a control byte which will be used
  61.  *        to locate the parameter when the macro is expanded.
  62.  * textput    puts a string in the macro work area (parm[]), updating
  63.  *        parmp to point to the first free byte in parm[].
  64.  *        textput() tests for work buffer overflow.
  65.  * charput    puts a single character in the macro work area (parm[])
  66.  *        in a manner analogous to textput().
  67.  */
  68. {
  69.     register int        c;
  70.     register DEFBUF        *dp;        /* -> new definition    */
  71.     int            isredefine;    /* TRUE if redefined    */
  72.     char            *old;        /* Remember redefined    */
  73.     extern int        save();        /* Save char in work[]    */
  74.  
  75.     if (type[(c = skipws())] != LET)
  76.         goto bad_define;
  77.     isredefine = FALSE;            /* Set if redefining    */
  78.     if ((dp = lookid(c)) == NULL)        /* If not known now    */
  79.         dp = defendel(token, FALSE);    /* Save the name    */
  80.     else {                    /* It's known:        */
  81.         isredefine = TRUE;            /* Remember this fact    */
  82.         old = dp->repl;            /* Remember replacement    */
  83.         dp->repl = NULL;            /* No replacement now    */
  84.     }
  85.     parlist[0] = parmp = parm;        /* Setup parm buffer    */
  86.     if ((c = get()) == '(') {        /* With arguments?    */
  87.         nargs = 0;                /* Init formals counter    */
  88.         do {                /* Collect formal parms    */
  89.         if (nargs >= LASTPARM)
  90.             cfatal("Too many arguments for macro", NULLST);
  91.         else if ((c = skipws()) == ')')
  92.             break;            /* Got them all        */
  93.         else if (type[c] != LET)    /* Bad formal syntax    */
  94.             goto bad_define;
  95.         scanid(c);            /* Get the formal param    */
  96.         parlist[nargs++] = parmp;    /* Save its start    */
  97.         textput(token);            /* Save text in parm[]    */
  98.         } while ((c = skipws()) == ',');    /* Get another argument    */
  99.         if (c != ')')            /* Must end at )    */
  100.         goto bad_define;
  101.         c = ' ';                /* Will skip to body    */
  102.     }
  103.     else {
  104.         /*
  105.          * DEF_NOARGS is needed to distinguish between
  106.          * "#define foo" and "#define foo()".
  107.          */
  108.         nargs = DEF_NOARGS;            /* No () parameters    */
  109.     }
  110.     if (type[c] == SPA)            /* At whitespace?    */
  111.         c = skipws();            /* Not any more.    */
  112.     workp = work;                /* Replacement put here    */
  113.     inmacro = TRUE;                /* Keep \<newline> now    */
  114.     while (c != EOF_CHAR && c != '\n') {    /* Compile macro body    */
  115. #if OK_CONCAT
  116. #if COMMENT_INVISIBLE
  117.         if (c == COM_SEP) {            /* Token concatenation? */
  118.         save(TOK_SEP);            /* Stuff a delimiter    */
  119.         c = get();
  120. #else
  121.         if (c == '#') {            /* Token concatenation?    */
  122.             int q;
  123.  
  124.             if (get()=='#') q=0; else { q=1; unget(); }
  125.         while (workp > work && type[workp[-1]] == SPA)
  126.             --workp;            /* Erase leading spaces    */
  127.         if (q) save(TOK_QUOTE); else save(TOK_SEP);    /* Stuff a delimiter    */
  128.         c = skipws();            /* Eat whitespace    */
  129. #endif
  130.         if (type[c] == LET)        /* Another token here?    */
  131.             ;                /* Stuff it normally    */
  132.         else if (type[c] == DIG) {    /* Digit string after?    */
  133.             while (type[c] == DIG) {    /* Stuff the digits    */
  134.             save(c);
  135.             c = get();
  136.             }
  137.             if (!q) save(TOK_SEP);        /* Delimit 2nd token    */
  138.         }
  139.         else {
  140. #if ! COMMENT_INVISIBLE
  141.             ciwarn("Strange character after # or ## (%d.)", c);
  142. #endif
  143.                     continue;
  144.                 }
  145.             }
  146. #endif
  147.         switch (type[c]) {
  148.         case LET:
  149.         checkparm(c, dp);        /* Might be a formal    */
  150.         break;
  151.  
  152.         case DIG:                /* Number in mac. body    */
  153.         case DOT:                /* Maybe a float number    */
  154.         scannumber(c, save);        /* Scan it off        */
  155.         break;
  156.  
  157.         case QUO:                /* String in mac. body    */
  158. #if STRING_FORMAL
  159.         stparmscan(c, dp);        /* Do string magic    */
  160. #else
  161.         stparmscan(c);
  162. #endif
  163.         break;
  164.  
  165.         case BSH:                /* Backslash        */
  166.         save('\\');
  167.         if ((c = get()) == '\n')
  168.             wrongline = TRUE;
  169.         save(c);
  170.         break;
  171.  
  172.         case SPA:                /* Absorb whitespace    */
  173.         /*
  174.          * Note: the "end of comment" marker is passed on
  175.          * to allow comments to separate tokens.
  176.          */
  177.         if (workp[-1] == ' ')        /* Absorb multiple    */
  178.             break;            /* spaces        */
  179.         else if (c == '\t')
  180.             c = ' ';            /* Normalize tabs    */
  181.         /* Fall through to store character            */
  182.         default:                /* Other character    */
  183.         save(c);
  184.         break;
  185.         }
  186.         c = get();
  187.     }
  188.     inmacro = FALSE;            /* Stop newline hack    */
  189.     unget();                /* For control check    */
  190.     if (workp > work && workp[-1] == ' ')    /* Drop trailing blank    */
  191.         workp--;
  192.     *workp = EOS;                /* Terminate work    */
  193.     dp->repl = savestring(work);        /* Save the string    */
  194.     dp->nargs = nargs;            /* Save arg count    */
  195. #if DEBUG
  196.     if (debug)
  197.         dumpadef("macro definition", dp);
  198. #endif
  199.     if (isredefine) {            /* Error if redefined    */
  200.         if ((old != NULL && dp->repl != NULL && !streq(old, dp->repl))
  201.          || (old == NULL && dp->repl != NULL)
  202.          || (old != NULL && dp->repl == NULL)) {
  203. #ifdef STRICT_UNDEF
  204.         cerror("Redefining defined variable \"%s\"", dp->name);
  205. #else
  206.         cwarn("Redefining defined variable \"%s\"", dp->name);
  207. #endif
  208.         }
  209.         if (old != NULL)            /* We don't need the    */
  210.         free(old);            /* old definition now.    */
  211.     }     
  212.     return;
  213.  
  214. bad_define:
  215.     cerror("#define syntax error", NULLST);
  216.     inmacro = FALSE;            /* Stop <newline> hack    */
  217. }
  218.  
  219. checkparm(c, dp)
  220. register int    c;
  221. DEFBUF        *dp;
  222. /*
  223.  * Replace this param if it's defined.  Note that the macro name is a
  224.  * possible replacement token.  We stuff DEF_MAGIC in front of the token
  225.  * which is treated as a LETTER by the token scanner and eaten by
  226.  * the output routine.  This prevents the macro expander from
  227.  * looping if someone writes "#define foo foo".
  228.  */
  229. {
  230.     register int        i;
  231.     register char        *cp;
  232.  
  233.     scanid(c);                /* Get parm to token[]    */
  234.     for (i = 0; i < nargs; i++) {        /* For each argument    */
  235.         if (streq(parlist[i], token)) {    /* If it's known    */
  236.         save(i + MAC_PARM);        /* Save a magic cookie    */
  237.         return;                /* And exit the search    */
  238.         }
  239.     }
  240.     if (streq(dp->name, token))        /* Macro name in body?    */
  241.         save(DEF_MAGIC);            /* Save magic marker    */
  242.     for (cp = token; *cp != EOS;)        /* And save        */
  243.         save(*cp++);            /* The token itself    */
  244. }
  245.  
  246. #if STRING_FORMAL
  247. stparmscan(delim, dp)
  248. int        delim;
  249. register DEFBUF    *dp;
  250. /*
  251.  * Scan the string (starting with the given delimiter).
  252.  * The token is replaced if it is the only text in this string or
  253.  * character constant.  The algorithm follows checkparm() above.
  254.  * Note that scanstring() has approved of the string.
  255.  */
  256. {
  257.     register int        c;
  258.  
  259.     /*
  260.      * Warning -- this code hasn't been tested for a while.
  261.      * It exists only to preserve compatibility with earlier
  262.      * implementations of cpp.  It is not part of the Draft
  263.      * ANSI Standard C language.
  264.      */
  265.     save(delim);
  266.     instring = TRUE;
  267.     while ((c = get()) != delim
  268.          && c != '\n'
  269.          && c != EOF_CHAR) {
  270.         if (type[c] == LET)            /* Maybe formal parm    */
  271.         checkparm(c, dp);
  272.         else {
  273.         save(c);
  274.         if (c == '\\')
  275.             save(get());
  276.         }
  277.     }
  278.     instring = FALSE;
  279.     if (c != delim)
  280.         cerror("Unterminated string in macro body", NULLST);
  281.     save(c);
  282. }
  283. #else
  284. stparmscan(delim)
  285. int        delim;
  286. /*
  287.  * Normal string parameter scan.
  288.  */
  289. {
  290.     register char        *wp;
  291.     register int        i;
  292.     extern int        save();
  293.  
  294.     wp = workp;            /* Here's where it starts    */
  295.     if (!scanstring(delim, save))
  296.         return;            /* Exit on scanstring error    */
  297.     workp[-1] = EOS;        /* Erase trailing quote        */
  298.     wp++;                /* -> first string content byte    */ 
  299.     for (i = 0; i < nargs; i++) {
  300.         if (streq(parlist[i], wp)) {
  301.         *wp++ = MAC_PARM + PAR_MAC;    /* Stuff a magic marker    */
  302.         *wp++ = (i + MAC_PARM);        /* Make a formal marker    */
  303.         *wp = wp[-3];            /* Add on closing quote    */
  304.         workp = wp + 1;            /* Reset string end    */
  305.         return;
  306.         }
  307.     }
  308.     workp[-1] = wp[-1];        /* Nope, reset end quote.    */
  309. }
  310. #endif
  311.  
  312. doundef()
  313. /*
  314.  * Remove the symbol from the defined list.
  315.  * Called from the #control processor.
  316.  */
  317. {
  318.     register int        c;
  319.  
  320.     if (type[(c = skipws())] != LET)
  321.         cerror("Illegal #undef argument", NULLST);
  322.     else {
  323.         scanid(c);                /* Get name to token[]    */
  324.         if (defendel(token, TRUE) == NULL) {
  325. #ifdef STRICT_UNDEF
  326.         cwarn("Symbol \"%s\" not defined in #undef", token);
  327. #endif
  328.         }
  329.     }
  330. }
  331.  
  332. textput(text)
  333. char        *text;
  334. /*
  335.  * Put the string in the parm[] buffer.
  336.  */
  337. {
  338.     register int    size;
  339.  
  340.     size = strlen(text) + 1;
  341.     if ((parmp + size) >= &parm[NPARMWORK])
  342.         cfatal("Macro work area overflow", NULLST);
  343.     else {
  344.         strcpy(parmp, text);
  345.         parmp += size;
  346.     }
  347. }
  348.  
  349. charput(c)
  350. register int    c;
  351. /*
  352.  * Put the byte in the parm[] buffer.
  353.  */
  354. {
  355.     if (parmp >= &parm[NPARMWORK])
  356.         cfatal("Macro work area overflow", NULLST);
  357.     else {
  358.         *parmp++ = c;
  359.     }
  360. }
  361.  
  362. /*
  363.  *        M a c r o   E x p a n s i o n
  364.  */
  365.  
  366. static DEFBUF    *macro;        /* Catches start of infinite macro    */
  367.  
  368. expand(tokenp)
  369. register DEFBUF    *tokenp;
  370. /*
  371.  * Expand a macro.  Called from the cpp mainline routine (via subroutine
  372.  * macroid()) when a token is found in the symbol table.  It calls
  373.  * expcollect() to parse actual parameters, checking for the correct number.
  374.  * It then creates a "file" containing a single line containing the
  375.  * macro with actual parameters inserted appropriately.  This is
  376.  * "pushed back" onto the input stream.  (When the get() routine runs
  377.  * off the end of the macro line, it will dismiss the macro itself.)
  378.  */
  379. {
  380.     register int        c;
  381.     register FILEINFO    *file;
  382.     extern FILEINFO        *getfile();
  383.  
  384. #if DEBUG
  385.     if (debug)
  386.         dumpadef("expand entry", tokenp);
  387. #endif
  388.     /*
  389.      * If no macro is pending, save the name of this macro
  390.      * for an eventual error message.
  391.      */
  392.     if (recursion++ == 0)
  393.         macro = tokenp;
  394.     else if (recursion == RECURSION_LIMIT) {
  395.         cerror("Recursive macro definition of \"%s\"", tokenp->name);
  396.         fprintf(stderr, "(Defined by \"%s\")\n", macro->name);
  397.         if (rec_recover) {
  398.         do {
  399.             c = get();
  400.         } while (infile != NULL && infile->fp == NULL);
  401.         unget();
  402.         recursion = 0;
  403.         return;
  404.         }
  405.     }
  406.     /*
  407.      * Here's a macro to expand.
  408.      */
  409.     nargs = 0;                /* Formals counter    */
  410.     parmp = parm;                /* Setup parm buffer    */
  411.     switch (tokenp->nargs) {
  412.     case (-2):                /* __LINE__        */
  413.         for (file = infile; file != NULL; file = file->parent) {
  414.             if (file->fp != NULL) {
  415.                 sprintf(work, "%d", file->line);
  416.                 ungetstring(work);
  417.                 break;
  418.             }
  419.         }
  420.         break;
  421.  
  422.     case (-3):                /* __FILE__        */
  423.         for (file = infile; file != NULL; file = file->parent) {
  424.         if (file->fp != NULL) {
  425.             sprintf(work, "\"%s\"", (file->progname != NULL)
  426.             ? file->progname : file->filename);
  427.             ungetstring(work);
  428.             break;
  429.         }
  430.         }
  431.         break;
  432.  
  433.     default:
  434.         /*
  435.          * Nothing funny about this macro.
  436.          */
  437.         if (tokenp->nargs < 0)
  438.         cfatal("Bug: Illegal __ macro \"%s\"", tokenp->name);
  439.         while ((c = skipws()) == '\n')    /* Look for (, skipping    */
  440.         wrongline = TRUE;        /* spaces and newlines    */
  441.         if (c != '(') {
  442.         /*
  443.          * If the programmer writes
  444.          *    #define foo() ...
  445.          *    ...
  446.          *    foo [no ()]
  447.          * just write foo to the output stream.
  448.          */
  449.         unget();
  450.         cwarn("Macro \"%s\" needs arguments", tokenp->name);
  451.         fputs(tokenp->name, stdout);
  452.         return;
  453.         }
  454.         else if (expcollect()) {        /* Collect arguments    */
  455.         if (tokenp->nargs != nargs) {    /* Should be an error?    */
  456.             cwarn("Wrong number of macro arguments for \"%s\"",
  457.             tokenp->name);
  458.         }
  459. #if DEBUG
  460.         if (debug)
  461.             dumpparm("expand");
  462. #endif
  463.         }                /* Collect arguments        */
  464.     case DEF_NOARGS:        /* No parameters just stuffs    */
  465.         expstuff(tokenp);        /* Do actual parameters        */
  466.     }                /* nargs switch            */
  467. }
  468.  
  469. FILE_LOCAL int
  470. expcollect()
  471. /*
  472.  * Collect the actual parameters for this macro.  TRUE if ok.
  473.  */
  474. {
  475.     register int    c;
  476.     register int    paren;            /* For embedded ()'s    */
  477.     extern int    charput();
  478.  
  479.     for (;;) {
  480.         paren = 0;                /* Collect next arg.    */
  481.         while ((c = skipws()) == '\n')    /* Skip over whitespace    */
  482.         wrongline = TRUE;        /* and newlines.    */
  483.         if (c == ')') {            /* At end of all args?    */
  484.         /*
  485.          * Note that there is a guard byte in parm[]
  486.          * so we don't have to check for overflow here.
  487.          */
  488.         *parmp = EOS;            /* Make sure terminated    */
  489.         break;                /* Exit collection loop    */
  490.         }
  491.         else if (nargs >= LASTPARM)
  492.         cfatal("Too many arguments in macro expansion", NULLST);
  493.         parlist[nargs++] = parmp;        /* At start of new arg    */
  494.         for (;; c = cget()) {        /* Collect arg's bytes    */
  495.         if (c == EOF_CHAR) {
  496.             cerror("end of file within macro argument", NULLST);
  497.             return (FALSE);        /* Sorry.        */
  498.         }
  499.         else if (c == '\\') {        /* Quote next character    */
  500.             charput(c);            /* Save the \ for later    */
  501.             charput(cget());        /* Save the next char.    */
  502.             continue;            /* And go get another    */
  503.         }
  504.         else if (type[c] == QUO) {    /* Start of string?    */
  505.             scanstring(c, charput);    /* Scan it off        */
  506.             continue;            /* Go get next char    */
  507.         }
  508.         else if (c == '(')        /* Worry about balance    */
  509.             paren++;            /* To know about commas    */
  510.         else if (c == ')') {        /* Other side too    */
  511.             if (paren == 0) {        /* At the end?        */
  512.             unget();        /* Look at it later    */
  513.             break;            /* Exit arg getter.    */
  514.             }
  515.             paren--;            /* More to come.    */
  516.         }
  517.         else if (c == ',' && paren == 0) /* Comma delimits args    */
  518.             break;
  519.         else if (c == '\n')        /* Newline inside arg?    */
  520.             wrongline = TRUE;        /* We'll need a #line    */
  521.         charput(c);            /* Store this one    */
  522.         }                    /* Collect an argument    */
  523.         charput(EOS);            /* Terminate argument    */
  524. #if DEBUG
  525.         if (debug)
  526.             printf("parm[%d] = \"%s\"\n", nargs, parlist[nargs - 1]);
  527. #endif
  528.     }                    /* Collect all args.    */
  529.     return (TRUE);                /* Normal return    */
  530. }
  531.  
  532. FILE_LOCAL
  533. expstuff(tokenp)
  534. DEFBUF        *tokenp;        /* Current macro being expanded    */
  535. /*
  536.  * Stuff the macro body, replacing formal parameters by actual parameters.
  537.  */
  538. {
  539.     register int    c;            /* Current character    */
  540.     register char    *inp;            /* -> repl string    */
  541.     register char    *defp;            /* -> macro output buff    */
  542.     int        size;            /* Actual parm. size    */
  543.     char        *defend;        /* -> output buff end    */
  544.     int        string_magic;        /* String formal hack    */
  545.     FILEINFO    *file;            /* Funny #include    */
  546.     int        endquote;
  547.     extern FILEINFO    *getfile();
  548.  
  549.     file = getfile(NBUFF, tokenp->name);
  550.     inp = tokenp->repl;            /* -> macro replacement    */
  551.     defp = file->buffer;            /* -> output buffer    */
  552.     defend = defp + (NBUFF - 1);        /* Note its end        */
  553.     endquote = 0;
  554.     if (inp != NULL) {
  555.         while ((c = (*inp++ & 0xFF)) != EOS) {
  556.         if (c >= MAC_PARM && c <= (MAC_PARM + PAR_MAC)) {
  557.             string_magic = (c == (MAC_PARM + PAR_MAC));
  558.             if (string_magic)
  559.              c = (*inp++ & 0xFF);
  560.             /*
  561.              * Replace formal parameter by actual parameter string.
  562.              */
  563.             if ((c -= MAC_PARM) < nargs) {
  564.             size = strlen(parlist[c]);
  565.             if ((defp + size) >= defend)
  566.                 goto nospace;
  567.             /*
  568.              * Erase the extra set of quotes.
  569.              */
  570.             if (string_magic && defp[-1] == parlist[c][0]) {
  571.                 strcpy(defp-1, parlist[c]);
  572.                 defp += (size - 2);
  573.             }
  574.             else {
  575.                 strcpy(defp, parlist[c]);
  576.                 defp += size;
  577.             }
  578.             }
  579.             if (endquote) { if (defp+1 >= defend) goto nospace; *defp++=DBL_QUOTE; endquote=0; }
  580.         }
  581.         else if (defp >= defend) {
  582. nospace:        cfatal("Out of space in macro \"%s\" arg expansion",
  583.             tokenp->name);
  584.         }
  585.         else if (c == TOK_QUOTE)
  586.         {
  587.             *defp++ = DBL_QUOTE;
  588.             endquote = 1;
  589.                 }
  590.         else {
  591.             *defp++ = c;
  592.         }
  593.         }
  594.     }
  595.     *defp = EOS;
  596. #if DEBUG
  597.     if (debug > 1)
  598.         printf("macroline: \"%s\"\n", file->buffer);
  599. #endif
  600. }
  601.  
  602. #if DEBUG
  603. dumpparm(why)
  604. char        *why;
  605. /*
  606.  * Dump parameter list.
  607.  */
  608. {
  609.     register int    i;
  610.  
  611.     printf("dump of %d parameters (%d bytes total) %s\n",
  612.         nargs, parmp - parm, why);
  613.     for (i = 0; i < nargs; i++) {
  614.         printf("parm[%d] (%d) = \"%s\"\n",
  615.         i + 1, strlen(parlist[i]), parlist[i]);
  616.     }
  617. }
  618. #endif
  619.